<template>
  <!--确认跳过本题-->
  <n-modal
    v-model:show="showSkipModal"
    transform-origin="center"
    preset="card"
    title="提示"
    class="w-600"
  >
    <template #default>
      <div>
        <div v-if="skipFlag"><b>即将抽下一题，请预留足够时间。</b></div>
        <div v-else><b>本关仅一题未完成，请继续本题，或点击我要通关</b></div>
      </div>
    </template>
    <template #footer>
      <!--        跳过本题成功-->
      <n-space justify="space-around" v-if="skipFlag">
        <n-button type="primary" @click="drawPro">我要抽题</n-button>
        <n-button type="default" @click="showSkipModal = false">暂且返回</n-button>
      </n-space>
      <!--        跳过本题不成功-->
      <div v-else>
        <n-button type="button" class="btn btn-default" @click="showSkipModal = false">
          确定
        </n-button>
      </div>
    </template>
  </n-modal>
  <!--    是否确定跳过本题-->
  <n-modal
    v-model:show="askSkipProblem"
    transform-origin="center"
    preset="card"
    title="提示"
    class="w-600"
  >
    <div>
      <p>
        如果过关时，本关有未完成的题目，每道未完成的题将扣本关的总分1%。跳过本题后，可以到“做题记录”里继续完成本题。
      </p>
      <p class="color-red">你确认要暂时跳过本题吗？</p>
    </div>
    <div align="right">
      <n-button type="default" @click="cancelAskSkip" class="mr-10">取消</n-button>
      <n-button type="primary" @click="sureToSkipProblem">确定</n-button>
    </div>
  </n-modal>
  <!--我要通关-->
  <n-modal
    v-model:show="showPassResultModal"
    transform-origin="center"
    preset="card"
    title="选择下一关"
    class="w-600"
  >
    <template #default>
      <div>
        <div class="mt-10">
          <div>切换到题目类别:</div>
          <n-select v-model:value="selectValue" :options="options" @update-value="handleSelect" />
        </div>
        <div class="mt-5 color-gray-500">
          <div v-if="catDesc.length > 0">类别描述：{{ catDesc }}</div>
          <div v-if="timeLimit.length > 0">时间限制： {{ timeLimit }}</div>
        </div>
      </div>
      <div class="mt-10">
        <b>注意：一旦抽取新题，即开始计时。请预留足够时间才开始做题。</b>
      </div>
    </template>
    <template #footer>
      <n-space justify="space-around">
        <n-button type="primary" @click="drawNext">我要抽题</n-button>
        <n-button type="default" @click="showPassResultModal = false">暂且返回</n-button>
      </n-space>
    </template>
  </n-modal>
  <!--  通关要求提示-->
  <n-modal
    v-model:show="passTip"
    transform-origin="center"
    preset="card"
    title="提示"
    class="w-600"
  >
    <div v-if="points < 1">
      <p>
        只有在实在做不出题目的情况下，才使用“我要通关”功能。一旦通关，本关将计算分数并计入总分。这之后本关不可再做题。是否确认通关？
      </p>
    </div>
    <div align="right">
      <n-button type="default" @click="passTip = false" class="mr-10">取消</n-button>
      <n-button type="primary" @click=";(askPassModal = true), (passTip = false)">确定</n-button>
    </div>
  </n-modal>
  <!--  确定是否通关-->
  <n-modal
    v-model:show="askPassModal"
    transform-origin="center"
    preset="card"
    title="提示"
    class="w-600"
  >
    <div v-if="points < 1">
      <p>
        本关尚未达到通关条件，确认通关吗？如果通关，将根据本关已完成的题目计算分数.
        预估所得分数不超过本关总分的{{ scoreconf * 100 }}%
      </p>
    </div>
    <div v-if="points >= 1">确定通关？</div>
    <div align="right">
      <n-button type="default" @click="askPassModal = false" class="mr-10">取消</n-button>
      <n-button type="primary" @click="sureToSkipCategory">确定</n-button>
    </div>
  </n-modal>
  <div class="ml-20">
    <n-space class="mt-20">
      <n-button type="info" @click="skipThisProblem">{{ skipButton }}</n-button>
      <n-button type="info" @click="passThisCategory" :disabled="passDisabled">我要通关</n-button>
    </n-space>
    <n-space class="mt-20 flex items-center">
      <span>切换到题目类别:</span>
      <n-select
        v-model:value="selectedCategory"
        placeholder="请选择切换类型"
        class="w-230 ml-5"
        :options="options_1"
        @update-value="handleSelect_1"
      ></n-select>
      <n-button type="info" class="ml-5" @click="changeCat" :disabled="changeDisable">
        切换
      </n-button>
    </n-space>
    <div class="mt-5 color-gray-500">
      <div v-if="catDesc_1.length > 0">类别描述：{{ catDesc_1 }}</div>
      <div v-if="timeLimit_1.length > 0">时间限制：{{ timeLimit_1 }}</div>
    </div>

    <div class="mt-30">
      <div>
        <label>注意：</label>
        <ol>
          <li>1、一旦抽取新题，即开始计时。请预留足够时间才开始做题。</li>
          <li>2、如果点“我要通关”，将根据本关已完成的题目计算分数</li>
        </ol>
      </div>
    </div>
  </div>
</template>

<script setup>
import api from '@/api/user'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router/dist/vue-router'
import { STATUS } from '@/constant'
import { drawProblem } from './utils'

const name = ref('')
const skipButton = ref('')
const finished = ref('') //当前关卡状态
const points = ref(0) //关卡分数
const probFinished = ref([]) //当前关卡中已完成的题目序号
const passDisabled = ref(false)
const changeDisable = ref(false)
const showSkipModal = ref(false) // 控制跳过本题弹窗显示
const askSkipProblem = ref(false) //确认是否跳过本题
const passTip = ref(false) //跳关提示
const askPassModal = ref(false) //确认是否跳过本关
const scoreconf = ref(0) //分数打折
const skipFlag = ref('')
const showPassResultModal = ref(false) //控制抽题弹窗展示
const options = ref([]) // 我要通关下拉框选项
const selectValue = ref(null) // 我要通关下拉框选中的值
const catDesc = ref('') // 题目类别描述
const timeLimit = ref('') //时间限制描述
const selectedCategory = ref(null)
const options_1 = ref([])
const catDesc_1 = ref('') // 题目类别描述
const timeLimit_1 = ref('') //时间限制描述
const route = useRoute()
const router = useRouter()
const { examId, problemId } = route.params
const catId = ref(0)
const curproblem = ref([])
//从url中获取catId
const getUrlkey = () => {
  // 第1步：获取当前URL
  const currentUrl = window.location.href

  // 第2步：从URL中提取查询字符串。这里我们先分割字符串获取哈希部分，
  // 然后再从哈希部分获取查询字符串
  const queryString = currentUrl.split('?')[1] // 这假设URL中只有一个'?'字符

  if (queryString) {
    // 第3步：使用URLSearchParams解析查询字符串
    const urlParams = new URLSearchParams(queryString)
    catId.value = urlParams.get('catId')
  } else {
    console.log('No query string found.')
  }
}
// 暂时跳过本题
const skipThisProblem = async () => {
  //判断本题是否已提交 或 本题已AC且在提醒后提交 或本关已通关 则可以直接跳关否则进入askSkipProblem
  if (
    curproblem.value.finished ||
    (finished && curproblem.status === STATUS.AC && isInProbfinished())
  ) {
    try {
      const res = await api.skipThisProblem({
        params: {
          examId: examId,
          proId: problemId,
          secCatgory_id: catId.value,
        },
      })
      //确定跳过后提示界面
      showSkipModal.value = true

      if (res.message === 'success') {
        skipFlag.value = true
      } else {
        skipFlag.value = false
      }
    } catch (error) {
      console.log(error)
    }
  } else askSkipProblem.value = true
}
//我要通关
const passThisCategory = async () => {
  getCategoryInfo() //获取页面题目信息
  scoreconf.value = parseFloat(points.value)
  scoreconf.value = Math.round(scoreconf.value * 100) / 100
  if (finished.value === true) {
    $message.info('本关已通关！')
  } else {
    if (points.value > 1) askPassModal.value = true
    else passTip.value = true
  }
}

const sureToSkipCategory = async () => {
  askPassModal.value = false
  try {
    const res = await api.passThisCategory({
      examId: examId,
      catId: catId.value,
    })
    //成功跳过本关后，跳过和通关按钮禁用
    passDisabled.value = true
    //通关后的抽题界面
    showPassResultModal.value = true
    const rows = res.data
    var localOptions = rows.map((row) => ({
      label: `(${row.rowX}.${row.colY}) ${row.name1}->${row.name2}`,
      value: row.catId,
    }))
    options.value = [...localOptions]
    getCanChangeCategory() //刷新跳转下拉框
  } catch (error) {
    console.log(error)
  }
}

//获取页面类别所需信息
const getCategoryInfo = async () => {
  try {
    const res = await api.getCategoryInfo({
      examId: examId,
      catId: catId.value,
    })

    name.value = res.data.name
    finished.value = res.data.finished
    points.value = res.data.points
    probFinished.value = res.data.ProbFinished
    if (finished.value) passDisabled.value = true
  } catch (error) {
    console.log(error)
  }
}
//获取题目状态
const getTrainProbdetailStatus = async () => {
  try {
    const res = await api.getTrainProbdetailStatus({
      examId: examId,
      id: problemId,
    })
    curproblem.value = res.data
  } catch (error) {
    console.log(error)
  }
}
const isInProbfinished = async () => {
  if (typeof probFinished == 'undefined') return false

  var proArr = probFinished.split(',')
  var index = proArr.includes(problemId)
  return index
}
//获取可切换的下拉框选项
const getCanChangeCategory = async () => {
  try {
    const res = await api.getCanChangeCategory({
      examId: examId,
    })
    var rows = res.data.category
    var localOptions = []
    if (rows.length === 0) {
      localOptions.push({
        label: '无可切换类型',
        disabled: true,
      })
      changeDisable.value = true
    } else {
      localOptions = rows.map((row) => ({
        label: `(${row.rowX}.${row.colY}) ${row.name1}->${row.name2}`,
        value: row.catId,
      }))
    }
    options_1.value = [...localOptions]
  } catch (error) {
    console.log(error)
  }
}
const changeCat = () => {
  if (selectedCategory.value === null) {
    $message.info('请选择切换类型')
    return
  }
  drawProblem(examId, selectedCategory.value, router)
}
//下拉框选择改变回调
const handleSelect_1 = async (value) => {
  try {
    const res = await api.getCatDescriptionAndTimelimit({
      params: { secCatgory_id: value, examId: examId },
    })
    catDesc_1.value = res.data.description
    if (res.data.deadline != null)
      timeLimit_1.value =
        '晚于' +
        res.data.bestBefore +
        '后提交分数乘' +
        res.data.scoreCoef +
        '%/n' +
        '截止时间' +
        res.data.deadline
    else timeLimit_1.value = ''
  } catch (error) {
    console.log('获取类别描述信息和时间限制信息发生错误：`getCatDescriptionAndTimelimit`\n', error)
  }
}
//我要通关下拉框改变
const handleSelect = async (value) => {
  try {
    const res = await api.getCatDescriptionAndTimelimit({
      params: { secCatgory_id: value, examId: examId },
    })
    catDesc.value = res.data.description
    if (res.data.deadline != null)
      timeLimit.value =
        '晚于' +
        res.data.bestBefore +
        '后提交分数乘' +
        res.data.scoreCoef +
        '%/n' +
        '截止时间' +
        res.data.deadline
    else timeLimit.value = ''
  } catch (error) {
    console.log('获取类别描述信息和时间限制信息发生错误：`getCatDescriptionAndTimelimit`\n', error)
  }
}
const drawNext = () => {
  if (selectValue.value === 0) {
    $message.info('请选择切换类型')
    return
  }
  drawProblem(examId, selectValue.value, router)
}
//取消跳过本题
const cancelAskSkip = () => {
  askSkipProblem.value = false
}
//确定跳过本题
const sureToSkipProblem = async () => {
  askSkipProblem.value = false
  try {
    const res = await api.skipThisProblem({
      params: {
        examId: examId,
        proId: problemId,
        secCatgory_id: catId.value,
      },
    })
    showSkipModal.value = true
    if (res.message === 'success') {
      skipFlag.value = true
    } else skipFlag.value = false
  } catch (error) {
    console.log(error)
  }
}
// 跳过本题之后继续抽本关题目
const drawPro = () => {
  drawProblem(examId, catId.value, router)
}

watchEffect(() => {
  if (curproblem.value.finished) {
    skipButton.value = '抽取下一题'
  } else skipButton.value = '暂时跳过本题'
})
onMounted(() => {
  getCanChangeCategory() //获取下拉框信息
  getUrlkey()
  getTrainProbdetailStatus() //获取当前题目细节
  getCategoryInfo() //获取页面题目信息
})
</script>
